import {commonRoutes, getDynamicRoutes} from '@/router'
import useLoginUserStore from "@/store/modules/user.js";
import {allSidebarRoutes} from "@/router/sidebar/sidebar.js";
import {isNull} from "@/utils/validate.js";

const usePermissionStore = defineStore('permission', {
    state: () => ({
        routes: [],
        addRoutes: [],
        defaultRoutes: [],
        topBarRoutes: [],
        sidebarRoutes: []
    }),
    actions: {
        setRoutes(routes) {
            this.addRoutes = routes
            this.routes = commonRoutes.concat(routes)
        },
        setDefaultRoutes(routes) {
            this.defaultRoutes = commonRoutes.concat(routes)
        },
        setTopBarRoutes(routes) {
            this.topBarRoutes = routes
        },
        setSidebarRoutes(routes) {
            this.sidebarRoutes = routes
        },
        generateRoutes() {
            return new Promise(resolve => {
                let dynamicRoutes = filterDynamicRoutes()
                dynamicRoutes = [...dynamicRoutes, ...getDynamicRoutes()]
                this.setRoutes(dynamicRoutes)
                this.setSidebarRoutes([...commonRoutes, ...dynamicRoutes])
                this.setDefaultRoutes(dynamicRoutes)
                this.setTopBarRoutes(dynamicRoutes)
                resolve(dynamicRoutes)
            })
        }
    }
})

function filterNestedRoutes(routes) {
    return routes.reduce((acc, route) => {
        // 检查第一层路由是否满足条件
        if (condition(route)) {
            // 如果路由有子路由，则递归过滤这些子路由
            const filteredChildren = (route.children && route.children.length > 0) ? filterNestedRoutes(route.children) : []
            acc.push({ ...route, children: filteredChildren })
        }
        // 如果第一层路由不满足条件，则不添加到结果数组中
        return acc
    }, [])
}

//登录用户的权限
let permissions = []

//路由的筛选条件
const condition = (route) => {
    return isNull(route.permissions) || permissions.indexOf(route.permissions[0]) >= 0
}

//过滤动态路由
function filterDynamicRoutes() {
    permissions = useLoginUserStore().permissions
    // 使用筛选函数
    return filterNestedRoutes(allSidebarRoutes)
}

export default usePermissionStore
